package com.fq.ioc.annotation.processor;

import com.fq.ioc.annotation.Component;
import com.fq.ioc.annotation.Value;
import com.fq.ioc.reflect.ObjectPool;
import com.fq.ioc.reflect.ObjectPoolBuilder;
import com.fq.ioc.utils.SimpleValueSetUtils;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author jifang
 * @since 16/1/6上午11:05.
 */
public class BeanProcessor {

    private static final ObjectPool POOL = ObjectPoolBuilder.init(null);

    public static void processObject(String clazz) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class targetClass = Class.forName(clazz);
        // 如果出现了Component注解, 说明是一个bean
        if (targetClass.isAnnotationPresent(Component.class)) {
            Object targetObject = targetClass.newInstance();
            // 注入属性值
            for (Field field : targetClass.getDeclaredFields()) {
                if (field.isAnnotationPresent(Value.class)) {
                    field.setAccessible(true);
                    Value value = field.getAnnotation(Value.class);
                    // 如果value有效(String或其他八种基本类型)
                    if (StringUtils.isNoneBlank(value.value())) {
                        SimpleValueSetUtils.setSimpleValue(field, targetObject, value.value());
                    } else if (StringUtils.isNoneBlank(value.ref())) {
                        Object valueObject = POOL.getObject(value.ref());
                        field.set(targetObject, valueObject);
                    } else {
                        throw new RuntimeException("neither value nor ref");
                    }
                }
            }

            Component component = (Component) targetClass.getAnnotation(Component.class);
            POOL.putObject(component.id(), targetObject);
        }
    }
}
